package domain;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import toolkit.Debug;
import domain.entity.Pizza;

public class PizzaManager implements Serializable
{
	private static final long serialVersionUID = 1L;

	public HashSet<Pizza> getPizzas()
	{
		return Pizza.getPizzas();
	}
	
	public Pizza getPizza(String name)
	{
		return Pizza.getPizza(name);
	}
	
	public Pizza removePizza(String name)
	{
		return Pizza.removePizza(name);
	}
	
	public HashMap<String, Object> getEntityValues(Object entity)
	{
		HashMap<String, Object> values = new HashMap<String, Object>();
		
		Map<String, Method> getters = getMethodsByPrefix(entity, "get");
		
		for (String key: getters.keySet())
		{
			try
			{
				values.put(key,getters.get(key).invoke(entity, new Object[0]));
			}
			catch (Exception e)
			{
				Debug.log(e);
			}
		}
		
		return values;
	}
	
	public void populateEntity(Object entity, Map<String, Object> values)
	{
		Map<String, Method> setters = getMethodsByPrefix(entity, "set");
		
		for (String key: setters.keySet())
		{
			try
			{
				if (values.containsKey(key))
				{
					setters.get(key).invoke(entity, values.get(key));
				}
			}
			catch (Exception e)
			{
				Debug.log(e);
			}
		}
	}
	
	private Map<String, Method> getMethodsByPrefix(Object entity, String prefix)
	{
		Map<String, Method> methods = new HashMap<String, Method>();
		
		int prefixLength = prefix.length();
		
		for (Method method: entity.getClass().getDeclaredMethods())
		{
			String name = method.getName();
			
			if (name.startsWith(prefix) && name.length() > prefixLength)
			{
				// For example: getAddress => address
				name = name.substring(prefixLength, prefixLength + 1).toLowerCase() + name.substring(prefixLength + 1);
				
				methods.put(name, method);
			}
		}
		
		return methods;
	}
}
